package com.transino.bop.context;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import com.transino.bop.domain.Catalog;
import com.transino.bop.domain.Category;
import com.transino.bop.domain.Entity;
import com.transino.bop.domain.Property;
import com.transino.bop.domain.PropertyGroup;
import com.transino.bop.factory.EntityFactory;

public abstract class AppContext implements EntityFactory {

	protected Catalog catalog;
	protected Map<String,Category> categoryIndex = new HashMap<String,Category>();
	protected Map<String,Entity> entityIndex = new HashMap<String,Entity>();
	protected Map<String,PropertyGroup> groupIndex = new HashMap<String,PropertyGroup>();
	protected Map<String,Property> propertyIndex = new HashMap<String,Property>();
	protected Properties properties;
	protected Date startDate;

	@Override
	public void setCatalog(Catalog catalog) {
		this.catalog = catalog;
		if(catalog != null) {
			for(Category category:catalog.getCategories()) {
				registerCategories(category);
			}
		}
	}

	@Override
	public Catalog getCatalog() {
		return this.catalog;
	}

	@Override
	public void registerCategory(Category category) {
		categoryIndex.put(category.getId(), category);
	}

	public void registerCategories(Category category) {
		if(category != null) {
			registerCategory(category);
			for(Category cate:category.getSubCategories()) {
				registerCategories(cate);
			}
		}
	}

	@Override
	public Category getCategory(String cid) {
		return categoryIndex.get(cid);
	}

	@Override
	public void registerEntity(Entity entity) {
		entityIndex.put(entity.getId(), entity);
	}

	@Override
	public List<Category> listCategories() {
		return new ArrayList<Category>(categoryIndex.values());
	}

	@Override
	public String getProperty(String key) {
		return this.properties.getProperty(key);
	}

	@Override
	public void setProperties(Properties properties) {
		this.properties = properties;
	}

	@Override
	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}

	@Override
	public Date getStartDate() {
		return startDate;
	}

	@Override
	public Entity getEntity(String key) {
		return entityIndex.get(key);
	}

	@Override
	public void registerGroup(PropertyGroup group) {
		this.groupIndex.put(group.getId(), group);
	}
	
	@Override
	public PropertyGroup getGroup(String key) {
		return groupIndex.get(key);
	}

	@Override
	public void registerProperty(Property property) {
		this.propertyIndex.put(property.getName(), property);
	}
	
	@Override
	public Property getPropertyById(String pid) {
		return propertyIndex.get(pid);
	}

	@Override
	public void modifyValidator(Entity e, Property p) {
		String validator = p.getValidator();
		e.setValidator(e.getValidator()+validator+",");
	}

}
